/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ufes.gpf.sgm.dao;

import edu.ufes.gpf.sgm.observer.Observado;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

/**
 *
 * @author Odair / Guilherme
 */
public abstract class AbstractDAOMySQL<E> implements Observado {

    private Connection conexao = null;
    private String host = "localhost";
    private String banco = "sgm";
    private String usuario = "root";
    private String senha = "1234";

    /**
     * @return Connection
     */
    public Connection conectar() throws ClassNotFoundException, SQLException {
        if (this.conexao == null) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String endereco = "jdbc:mysql://" + host + "/" + banco;
                this.conexao = DriverManager.getConnection(endereco, usuario, senha);
                return this.conexao;
            } catch (ClassNotFoundException cfe) {
                throw cfe;
            } catch (SQLException se) {
                throw se;
            }
        }

        return this.conexao;

    }

    /**
     *
     * @return boolean
     */
    public boolean desconectar() throws SQLException {

        boolean retorno = false;

        if (this.conexao != null) {
            try {
                this.conexao.close();
                retorno = true;
            } catch (SQLException se) {
                throw se;
            }
        }

        return retorno;

    }

    /**
     *
     * @param pConsulta
     * @return ResultSet
     */
    public ResultSet consultar(String pConsulta) throws SQLException {

        ResultSet retorno = null;

        if (this.conexao != null) {
            Statement stm = this.conexao.prepareStatement(pConsulta);
            PreparedStatement preStm = this.conexao.prepareStatement(pConsulta);
            try {
                retorno = stm.executeQuery(pConsulta); // Tenta executar uma consulta contendo SELECT
            } catch (SQLException se1) {
                try {
                    preStm.executeUpdate(); // Tenta executar uma consulta contendo INSERT, UPDATE, ALTER
                } catch (SQLException se2) {
                    throw se2;
                }
            }

        }

        return retorno;

    }

    public abstract boolean salvar(E pObjeto);

    public abstract boolean atualizar(E pObjeto);

    public abstract boolean remover(E pObjeto);

    public abstract E buscarPorId(int pObjetoId);
    
    public abstract int ultimoObjectIdentifier();

    public abstract Collection<E> buscarTodos();
}
